import cv2
import numpy as np

cap = cv2.VideoCapture('../../IMAGES/video_mask.avi')

ret, frame = cap.read()
print("frame:", frame.shape)
cv2.imshow("frame", frame)
cv2.waitKey(0)

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (250, 175))

lower_blue = np.array([100, 50, 50])
upper_blue = np.array([120, 255, 255])

kernel = np.ones((5, 5), np.uint8)

font = cv2.FONT_HERSHEY_SIMPLEX

if cap.isOpened():
    open, frame = cap.read()
else:
    open = False

while open:
    ret, frame = cap.read()

    if ret:
        frame_roi = frame[300:475, 150:400]

        hsv = cv2.cvtColor(frame_roi, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(hsv, lower_blue, upper_blue)
        ret, mask_frame = cv2.threshold(mask, 25, 255, cv2.THRESH_BINARY)
        mask_frame = cv2.morphologyEx(mask_frame, cv2.MORPH_OPEN, kernel)

        mask_frame = cv2.dilate(mask_frame, kernel, iterations=1)

        dst = cv2.bitwise_and(frame_roi, frame_roi, mask = mask_frame)

        _, contours, _ = cv2.findContours(mask_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        for c in contours:
            x, y, w, h = cv2.boundingRect(c)
            cv2.rectangle(dst, (x, y), (x + w, y + h), (0, 255, 0), 2)

            cv2.putText(dst, 'kouzhao', (x, y), font, 1, (255, 255, 255), 2)

        out.write(dst)

        cv2.imshow("original video", frame_roi)
        cv2.imshow("noise video", mask)
        cv2.imshow("denoise video", mask_frame)
        cv2.imshow("dst video", dst)
        cv2.waitKey(100)
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()
